<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 用户模型
 *
 * @author www.dingwei.cn
 */

class ConsumerUserModel extends MY_Model{
	
	public $tbUser = 'consumer';
	public $tbSession = 'consumer_session';
	public $tbVerifyCode = 'consumer_verify_code';
	public $tbBuyLog = 'consumer_buy_log'; //购买记录
	
	public $tbCollection= 'consumer_collection';//收藏列表

	/**
	 * 添加发送短信验证码记录
	 *
	 * @param	string	$mobile	手机号码
	 * @param	string	$code	编号
	 * @return	boolean
	 */
	public function addSmsCodeLog($mobile, $code){
	
		if( ! $mobile || ! $code){
			return false;
		}
	
		$data = array(
				'mobile' => $mobile,
				'code' => $code,
				'addtime' => time()
		);
	
		$this->db->where(array('mobile' => $mobile));
		$tI = $this->count($this->tbVerifyCode);
		$query = false;
		if($tI){
			$this->db->where(array('mobile' => $mobile));
			$query = $this->update($this->tbVerifyCode, $data);
		}else{
			$query = $this->insert($this->tbVerifyCode, $data);
		}
	
		if($query){
			return true;
		}
	
		return false;
	}
	
	/**
	 * 获取验证码发送日志
	 *
	 * @param	string	$mobile	手机号码
	 * @param	string	$code	验证码
	 * @return	array
	 */
	public function getSmsCodeLogInfo($mobile, $code = ''){
	
		if( ! $mobile){
			return array();
		}
	
		$this->db->where(array('mobile' => $mobile));
		if($code){
			$this->db->where(array('code' => $code));
		}
		$tA = $this->getOne($this->tbVerifyCode);
		if( ! $tA){
			return array();
		}
	
		return $tA;
	}
	
	/**
	 * 清空验证码
	 *
	 * @param	string	$mobile	手机号码
	 * @return	boolean
	 */
	public function deleteSmsCode($mobile){
	
		if( ! $mobile) return false;
		$this->db->where(array('mobile' => $mobile));
		if($this->update($this->tbVerifyCode, array('code' => ''))){
			return true;
		}
	
		return false;
	}
	
	/**
	 * 判断电话号码是否存在
	 *
	 * @param	string	$mobile	//手机号码
	 * @return	boolean (false:不存在   true:存在)
	 */
	public function mobileIsExist($mobile, $notId = 0){
			
		if( ! $mobile) return false;
		$this->db->select('id')->where(array('mobile' => $mobile));
		if($notId){
			$this->db->where(array('id <>' => $notId));
		}
        $this->db->where(array('status >' => 0));

		$tA = $this->getOne($this->tbUser);
		if($tA){
			return $tA['id'];
		}
			
		return false;
	}

	/**
	 * 通过openid验证用户是否存在
	 * @param	string	$openid	//手机号码
	 * @return	boolean (false:不存在   true:存在)
	 */
	public function openidIsExist($openid){

		if( ! $openid) return false;
		$this->db->select('id')->where(array('openid' => $openid));
        $this->db->where(array('status >' => 0));

		$tA = $this->getOne($this->tbUser);
		if($tA){
			return $tA['id'];
		}

		return false;
	}

	/**
	 * 添加登录信息
	 * 
	 * @param	integer	$userId		用户id
	 * @param	string	$sessionid	会话id
	 * @param	integer	$type		会话客服端类型（1:手机客户端  2: pc端）
	 * @return	boolean
	 */
	public function addSession($userId, $sessionid, $type = 1){
		
		$data = array(
					'consumer_id' => $userId,
					'sessionid' => $sessionid,
					'type' => $type,
					'addtime' => time(),
				);
				
		$this->db->where(array('consumer_id' => $userId, 'type' => $type));
		$tI = $this->count($this->tbSession);
		if($tI){
			$this->db->where(array('consumer_id' => $userId, 'type' => $type));
			if($this->update($this->tbSession, $data)){
				return true;
			}
		}else{
			if($this->insert($this->tbSession, $data)){
				return true;
			}
		}
		
		return false;
	}

	/**
	 * 删除sessionid
	 * @param 	integer $userId
	 * @param 	number 	$type
	 * @return	boolean
	 */
	public function deleteSession($userId, $type = 1){
		$this->db->where(array('user_id' => $userId, 'type' => $type));
		return $this->delete($this->tbSession);
	}
	
	/**
	 * 保存用户信息
	 *
	 * @param	array	$data	保存数据
	 * @param	integer $id		用户id
	 * @return	boolean
	 */
	public function save($data, $id = 0){
	
		if( ! $data) return false;
		if($id){
			$this->db->where(array('id' => $id));
			if($this->update($this->tbUser, $data)){
				return true;
			}
		}else{
			if($id = $this->insert($this->tbUser, $data)){
				return $id;
			}
		}
	}

    /**
     * 删除消费者
     * @param 	integer $userId
     * @return	boolean
     */
    public function deleteConsumer($userId){

        if(!$userId)return false;

        $this->db->where(array('id' => $userId));
        return $this->delete($this->tbUser);
    }

    /**
     * 获取消费者信息
     * @param $consumerIds 消费者ids
     * @return array
     * @author zyl
     */
    public function getInfoByIds($consumerIds){
    	
    	if( ! $consumerIds){
    		return array();
    	}
    	
    	$this->db
    	->select('id,realname,nickname,balance,integral,portrait,mobile,gender,status,addtime,jpush_code')
    	->where_in('id',$consumerIds);
    	
    	$tA = $this->getAll($this->tbUser);
    	
    	$tData = array();
    	foreach ($tA as $k=>$v){
    		$tA[$k]['portrait'] = $v['portrait'] ? getImage($v['portrait']) : getDefaultPortrait(1);
    		$tA[$k]['balance'] = $v['balance'] ? $v['balance'] : '0.00';
    		$tA[$k]['integral'] = $v['integral'] ? $v['integral'] : '0';
    		$tA[$k]['gender'] = $v['gender'] ? $this->getGender($v['gender']) : '保密';
	    	
    		$tData[$v['id']] = $tA[$k];
    	}
    	
    	return $tData;
    }
    
    /**
     * 获取消费者信息
     * @param $consumerId 消费者id
     * @return array
     */
	public function getInfo($consumerId){

        if( ! $consumerId){
            return array();
        }

		$this->db
		->select('id,realname,nickname,balance,integral,password,pay_passwd,portrait,mobile,gender,status,experience_value,
		addtime,message_push,jpush_code,last_login_time')
		->where('id',$consumerId);
		
		$tA = $this->getOne($this->tbUser);

		if($tA){
			$tA['has_pay_passwd'] = empty($tA['pay_passwd']) ? 1 : 2;
			$tA['nickname'] = $tA['nickname'] ?$tA['nickname'] : '暂无昵称';
			$tA['portrait'] = $tA['portrait'] ? getImage($tA['portrait']) : getDefaultPortrait(1);
            $tA['balance'] = $tA['balance'] ? $tA['balance'] : '0.00';
            $tA['integral'] = $tA['integral'] ? $tA['integral'] : '0';
            $tA['gender'] = $tA['gender'] ? $this->getGender($tA['gender']) : '保密';
        }

		return $tA;
	}
	
	/**
	 * 获取用户信息通过session
	 * 
	 * @param	string 	$sessionid	会话id
	 * @param	integer $type	(1：app 2：pc)
	 * @return	array
	 */
 	public function getInfoBySessionid($sessionid, $type = 1){
 	
 		if( ! $sessionid){
 			return array();
 		}
 		$this->db->select('u.id,u.portrait,u.nickname,u.openid,u.pay_passwd,u.balance,u.integral,u.experience_value,u.mobile,u.status,u.jpush_code')
 				 ->join($this->tbUser.' u', 'u.id = se.consumer_id')
 				 ->where(array('se.sessionid' => $sessionid, 'se.type' => $type));	
 				 
 		$tA = $this->getOne($this->tbSession.' se');
 		if( ! $tA){
 			return array();
 		}
 		return $tA;
 	} 
 	
 	/**
 	 * 获取用户Sessionid encode 加密后的
 	 *
 	 * @param	string 	$sessionid	会话id
 	 * @param	integer $type	(1：app 2：pc)
 	 * @return	array
 	 */
 	public function getSessionidByIds($Ids){
 		$this->db->select('consumer_id,sessionid')
 		->where_in('consumer_id',$Ids);
 		
 		$tA = $this->getAll($this->tbSession);
 		if( ! $tA){
 			return array();
 		}
 		$sessionid = array();
 		foreach ($tA as $k=>$v){
 			$sessionid[$v['consumer_id']] = encode($v['sessionid']);
 		}
 		return $sessionid;
 	} 
 	
 	/**
 	 * 获取用户信息
 	 * 
 	 * @param	string	$mobile		手机号码
 	 * @param	string	$password	密码
     * @param	array/string	    $where
     * @return 	array
 	 */
 	public function getInfoByMobileAndPassword($mobile, $password, $where = array()){

        if(! $mobile && ! $password){
            if (empty($where)){
                return array();
            }
        }
        if (!empty($where)){
            $this->db->where($where);
        }else{
            $this->db->where(array('mobile' => $mobile, 'password' => $password));
        }
        $this->db->where(array('status >'  => 0));
 		$this->db->select('id,nickname,mobile,status,pay_passwd,jpush_code,easemob_code,easemob_pwd');

 		$tA = $this->getOne($this->tbUser);

 		if(empty($tA)) $tA = array();
 		return $tA;
 	}

    /**
     * 获取用户性别
     * @param 	integer $status
     * @return	string
     */
    public function getGender($status = null, $show = false){

        $config = array(1 => '保密', 2 => '男', 3 => '女');
        if( ! $status){
            return $config;
        }

        if($status && ! isset($config[$status])){
            return '';
        }

        if( ! $show){
            return $config[$status];
        }

        return'';
    }

    /**
     * 字段自增删修改
     * @param int       $id
     * @param float     $number         数量
     * @param string    $field          字段
     * @param int       $type           1 增加  2 减少
     * @return bool
     * @author heyu
     */
    public function setConsumer($id, $number, $field = 'balance', $type = 1){
        if (! $id){
            return false;
        }
        $this->db->where(array('id' => $id));
        if($type==2){
            $this->db->set($field, $field.'-'.$number, FALSE);
        }else{
            $this->db->set($field, $field.'+'.$number, FALSE);
        }
        return $this->db->update($this->tbUser);
    }

    /**
     * 统计消费者
     * @param  integer $time       当月新增消费者
     * @return array
     * @author heyu
     */
    public function getTotalConsumer($time = 0){
        if ($time){
            $this->db->where('addtime > '.$time);
        }
        $this->db->where(array('status >' => 0));

        return $this->count($this->tbUser);
    }

    /////////////////////////////////////////////////////////////////
    //+-------------------------------------------------------------
    //|	获取收藏
    //+-------------------------------------------------------------
    
    /**
     * 获取某个分类的收藏量
     * @param integer $relationId 关联id
     * @param unknown $type
     * @return StdClass|array
     * @author zyl
     */
    public function getCollectionTotal($relationId = 0,$type = 0){
    	if (! $relationId && ! $type){
    		return 0;
    	}
    	//分类id
    	if ($relationId){
    		$this->db->where('relation_id',$relationId);
    	}
    	//类型 
    	if ($type){
    		$this->db->where('type',$type);
    	}
    	
    	return $this->count($this->tbCollection);
    }
    
    /**
     * 获取消费者收藏列表
     * @param integer   $consumerId   消费者id
     * @param integer   $type		    类型
     * @param integer   $page	        分页
     * @param string    $latitude
     * @param string    $longitude
     * @return array
     * @author zyl
     */
    public function appGetCollectionList($consumerId,$type,$page = 1,$latitude,$longitude){

        if ( ! $consumerId || ! $type){
            return array();
        }
        $this->db->where(array('consumer_id'=>$consumerId,'type'=>$type));

        $tA = $this->appPage($this->tbCollection, $page);

        //获取关联id
        $tRelationIds = array();
        foreach ($tA['list'] as $k=>$v){
            if (!in_array($v['relation_id'], $tRelationIds)){
                $tRelationIds[] = $v['relation_id'];
            }
        }

        if ( ! $tRelationIds){
            return array();
        }

        //获取关联的文章信息
        switch ($type){
            case 1:
                //获取店铺
                get_instance()->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
                $tData = $this->mMerchant->appGetShopList(0,0,0,$page,$tRelationIds,false,'',$latitude,$longitude);
                break;
            case 2:
                //便民服务
                get_instance()->loadModel('ConsumerFindModel', 'mFind', 'consumer');
                $tData = $this->mFind->appGetList(0, 0, 1, 999, $tRelationIds, 0, 0, 0);
                break;
            default:
                $tData = array();
        }

        return $tData;
    }
    
    /**
     * 检查收藏的是否存在
     * @param integer $consumerId 消费者id
     * @param integer $relationId 关联id
     * @param integer $type 类型
     * @return boolean
     * @author zyl
     */
    public function hasCollection($consumerId,$relationId,$type){
    	$this->db->where(array('consumer_id'=>$consumerId,'relation_id'=>$relationId,'type'=>$type));
    	$count = $this->count($this->tbCollection);
    	return $count > 0 ? true : false;
    }
    
    /**
     * 保存收藏
     * @param array $data 数据
     * @return boolean
     * @author zyl
     */
    public function saveCollection($data){
    	$query = $this->insert($this->tbCollection, $data);
    	return $query === false ? false : true;
    }
    
    /**
     * 移除收藏
     * @param integer $consumerId 消费者id
     * @param integer $relationId 关联id
     * @param integer $type 类型
     * @return boolean
     * @author zyl
     */
    public function removeCollection($consumerId,$relationId,$type){
    	$this->db->where(array('consumer_id'=>$consumerId,'relation_id'=>$relationId,'type'=>$type));
    	$query = $this->delete($this->tbCollection);
    	return $query === false ? false : true;
    }
    
 	/////////////////////////////////////////////////////////////////
 	//+-------------------------------------------------------------
 	//|	后台方法
 	//+-------------------------------------------------------------
 	
 	public function adminGetList($messagePush = 0,$all = false){
        $county = (int)get('county');
        $nickname = trim(get('nickname'));
        $realname= trim(get('realname'));
        $mobile= trim(get('mobile'));
        $gender= intval(get('gender'));
        $status= intval(get('status'));
        $send_date_from = strtotime(get('send_date_from'));
        $send_date_to = strtotime(get('send_date_to'));
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if($nickname){
            $this->db->like('u.nickname', $nickname);
        }

        if($realname){
            $this->db->like('u.realname', $realname);
        }

        if($mobile){
            $this->db->where('(u.mobile like "%'.$mobile.'%")');
        }

        if($gender){
            if ($gender == 1) {
                $this->db->where('u.gender', $gender)
                    ->or_where('u.gender is null');
            }else{
                $this->db->where('u.gender', $gender);
            }
        }

        if($status){
            $this->db->where('u.status', $status);
        }

        if ($messagePush){
            $this->db->where('u.message_push', $messagePush);
        }
        if($send_date_from){
            $this->db->where('u.addtime >=', $send_date_from);
        }
        if($send_date_to){
            $this->db->where('u.addtime <= ', strtotime('+1day', $send_date_to));
        }
        if($iSortCol_0 == 4){
            $this->db->order_by('u.balance '.$sSortDir_0);
        }elseif ($iSortCol_0 == 5){
            $this->db->order_by('IF(ISNULL(u.last_login_time),0,1) desc');//null强制放到最后
            $this->db->order_by('u.last_login_time '.$sSortDir_0);
        }elseif ($iSortCol_0 == 6){
            $this->db->order_by('IF(ISNULL(u.addtime),0,1) desc');//null强制放到最后
            $this->db->order_by('u.addtime '.$sSortDir_0);
        }elseif ($iSortCol_0 == 7){
            $this->db->order_by('IF(ISNULL(u.last_login_time),0,1) desc');//null强制放到最后
            $this->db->order_by('u.last_login_time '.$sSortDir_0);
        }

        if ($county){
            get_instance()->loadModel('ConsumerAddressModel', 'mAddress', 'consumer');
            $this->db->join($this->mAddress->tbAddress.' a', 'a.consumer_id=u.id')
                ->where(array('a.county' => $county, 'a.is_default' => 2));
        }
        $this->db->select('u.id,u.portrait,u.nickname,u.realname,u.mobile,u.balance,u.gender,u.addtime,u.last_login_time,u.status')
                 ->order_by('u.id desc')
            ->where(array('u.status >' => 0));
//        $this->pagination($this->tbUser.' u');
//        echo $this->db->last_query();
        if($all){
            return $this->getAll($this->tbUser.' u');
        }else{
 		    return $this->pagination($this->tbUser.' u');
        }

 	}


    /////////////////////////////////////////////////////////////////
    //+-------------------------------------------------------------
    //|	购买记录
    //+-------------------------------------------------------------
    public function appGetBuyLogList($consumerId, $type = 0, $time = 0, $page = 1){
    	
    	/**-----------------------------------------------------------------
    	 * 时间筛选
    	 */
    	$starttime = '';
    	$endtime = '';
    	//类型存在
    	if ( $type == 1 && ! $time){
    		//默认今天
    		$starttime = strtotime(date('Y-m-d 00:00:00'));
    		$endtime = strtotime('+ 1 day',$starttime);
    		
    	}else if ($type == 1 && $time){
    		//天
    		if ( ! strtotime($time)){
    			$this->appReturn(0,'时间格式错误');
    		}
    		$starttime = strtotime(date('Y-m-d 00:00:00',strtotime($time)));
    		$endtime = strtotime('+ 1 day',$starttime);
    		
    	}else if ($type == 2 && $time){
    		//月
    		if ( ! strtotime($time)){
    			$this->appReturn(0,'时间格式错误');
    		}
    		$starttime = strtotime(date('Y-m-01 00:00:00',strtotime($time)));
    		$endtime = strtotime('+ 1 month',$starttime);
    	}
    	//     	echo date('Y-m-d H:i:s',$starttime);
    	//     	echo date('Y-m-d H:i:s',$endtime);
    	
    	if ($starttime && $endtime){
    		$this->db->where(array('addtime >='=>$starttime,'addtime <'=>$endtime));
    	}
    	//---------------------------------------------------------------------
    	
    	
    	$this->db
    	->select('id,type,amount,status,addtime')
    	->where('consumer_id',$consumerId)
    	->order_by('id desc');
    	$tA = $this->appPage($this->tbBuyLog, $page);
    	
    	foreach ($tA['list'] as $k=>$v){
    		$tA['list'][$k]['title'] = $this->_buyType($v['type']); 
    		$tA['list'][$k]['amount'] = $this->_buyType($v['type'],true).$v['amount']; 
    		$tA['list'][$k]['addtime'] = date('Y-m-d',$v['addtime']); 
    		$tA['list'][$k]['status_desc'] = $v['status'] == 1 ? '失败':($v['status'] == 2 ? '成功':'申请中');
    	}
    	
    	return $tA['list'];
    }
    
    /**
     * 获取购买记录信息
     * @param integer $consumerId 消费者id
     * @param number $id 购买记录id
     * @param number $type 类型
     * @param string $like 搜索param
     * @return array|array
     * @author zyl
     */
    public function getBuyLogInfo($consumerId,$id = 0,$type = 0,$like = ''){
    	if ( ! $consumerId && ! $id){
    		return array();
    	}
    	
    	$this->db->where('consumer_id',$consumerId);
    	if ($id){
    		$this->db->where('id',$id);
    	}
    	if ($type){
    		$this->db->where('type',$type);
    	}
    	if ($like){
    		$this->db->like('param',$like);
    	}
    	
    	$this->db->select('id');
    	return $this->getOne($this->tbBuyLog);
    }
 	
    /**
     * 保存购买记录
     * @param array $data 数据
     * @param integer $id id
     * @return boolean|boolean|number
     * @author zyl
     */
    public function saveBuyLog($data,$id = 0){
    	
    	if ($id){
    		$this->db->where('id',$id);
    		$query = $this->update($this->tbBuyLog, $data);
    		return $query === false ? false : true;
    	}else{
    		return $this->insert($this->tbBuyLog, $data);
    	}
    }
    
    /**
     * 购买记录类型
     */
 	private function _buyType($key = NULL,$desc = FALSE){
 		$type = array(
 				1 => array('充值','+'),
 				2 => array('支付',''),
 				3 => array('退款','+'),
 				4 => array('提现',''),
 				5 => array('领取红包','+'),
 				6 => array('平台调整',''),
 				7 => array('分享收益',''),
 		);
 		
 		if ($key){
 		
 			if (isset($type[$key])){
 				if ($desc){
 					return $type[$key][1];
 				}
 				return $type[$key][0];
 			}
 			return '暂无类型';
 		}
 		
 		return $type;
 	}
 	
    /////////////////////////////////////////////////////////////////
    //+-------------------------------------------------------------
    //|	后台方法
    //+-------------------------------------------------------------
 	
}